package com.woniu.adapter;

import com.woniu.client.OrderClient;
import com.woniu.outlet.dao.OrderPoMapper;
import com.woniu.outlet.dao.ProPlanPoMapper;
import com.woniu.outlet.po.OrderPo;
import com.woniu.outlet.po.OrderPoExample;
import com.woniu.outlet.po.ProPlanPo;
import com.woniu.uitl.ProPlanStatus;
import com.woniu.uitl.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 生产计划适配层
 */
@Component
@Transactional
public class ProPlanAdapter {

    @Autowired
    private ProPlanPoMapper proPlanPoMapper;
    @Autowired
    private OrderPoMapper orderPoMapper;
    //添加生产计划
    public void addProPlan(ProPlanPo po) throws Exception{
        OrderPo orderPos = orderPoMapper.getOrderById(po.getOrderId());
        if (!orderPos.getOrderStatus().equals("待计划")){
            throw new Exception("该订单处于"+orderPos.getOrderStatus()+"，无法添加生产计划");
        }
        if (StringUtils.isEmpty(orderPos)){
            throw new Exception("无效的订单号");
        }
        SnowflakeIdGenerator idWorkes = new SnowflakeIdGenerator(1, 1);
        long id = idWorkes.nextId();
        long ProPlanNo = idWorkes.nextId();
        po.setId(id);
        po.setPlanNo(ProPlanNo);
        po.setStatus(ProPlanStatus.UNSUBMITTED.getStatus());
        po.setCreateTime(new Date());
        proPlanPoMapper.insertSelective(po);

        //改变订单状态
        String status = "已计划";
        orderPoMapper.updateOrderStatus(orderPos.getId(),status);
    }

    //修改生产计划
    public void updateProPlan(ProPlanPo po)throws Exception{
        ProPlanPo proPlanPo = proPlanPoMapper.selectByPrimaryKey(po.getId());
        if (StringUtils.isEmpty(proPlanPo)){
            throw new Exception("生产计划单不存在,请重新操作");
        }
        if (!proPlanPo.getStatus().equals(ProPlanStatus.UNSUBMITTED.getStatus())){
            throw new Exception("不支持此次操作,该生产计划已经在进行中或者已经完成");
        }
        proPlanPoMapper.updateByPrimaryKeySelective(po);
    }

    //删除生产计划单
    public void deleteProPlanById(Long id) throws Exception{
        if (StringUtils.isEmpty(id)){
            throw new Exception("请指定生产计划单id");
        }
        ProPlanPo proPlanPo = proPlanPoMapper.selectByPrimaryKey(id);
        if (StringUtils.isEmpty(proPlanPo)){
            throw new Exception("请指定生产计划单id");
        }
        if (!proPlanPo.getStatus().equals(ProPlanStatus.UNSUBMITTED.getStatus())){
            throw new Exception("不支持此次操作,该生产计划已经在进行中或者已经完成");
        }
        proPlanPoMapper.deleteByPrimaryKey(id);
    }
}
